package middleware

import (
	"net/http/pprof"

	"github.com/labstack/echo"
)

func Pprof(e *echo.Echo) {
	PprofGroup(e.Group(""))
}

// 让echo实现net/http/pprof的功能
func PprofGroup(group *echo.Group) {
	routes := []struct {
		Method  string
		Path    string
		Handler echo.HandlerFunc
	}{
		{"GET", "/debug/pprof/", Index()},
		{"GET", "/debug/pprof/heap", Handler("heap")},
		{"GET", "/debug/pprof/goroutine", Handler("goroutine")},
		{"GET", "/debug/pprof/block", Handler("block")},
		{"GET", "/debug/pprof/threadcreate", Handler("threadcreate")},
		{"GET", "/debug/pprof/mutex", Handler("mutex")},
		{"GET", "/debug/pprof/cmdline", Cmdline()},
		{"GET", "/debug/pprof/profile", Profile()},
		{"GET", "/debug/pprof/symbol", Symbol()},
		{"POST", "/debug/pprof/symbol", Symbol()},
		{"GET", "/debug/pprof/trace", Trace()},
	}

	for _, route := range routes {
		group.Add(route.Method, route.Path, route.Handler)
	}
}

func Index() echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Index(c.Response().Writer, c.Request())
		return nil
	}
}

func Cmdline() echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Cmdline(c.Response().Writer, c.Request())
		return nil
	}
}

func Profile() echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Profile(c.Response().Writer, c.Request())
		return nil
	}
}

func Symbol() echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Symbol(c.Response().Writer, c.Request())
		return nil
	}
}

func Trace() echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Trace(c.Response().Writer, c.Request())
		return nil
	}
}

func Handler(name string) echo.HandlerFunc {
	return func(c echo.Context) error {
		pprof.Handler(name).ServeHTTP(c.Response().Writer, c.Request())
		return nil
	}
}
